package com.module.overview.ui.widget;

import static com.common.base.app.extras.ViewExtKt.dp2px;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;

import com.common.base.utils.ViewUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.interfaces.IPickerViewData;
import com.contrarywind.listener.OnItemSelectedListener;
import com.module.overview.R;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 横向滚轮控件
 */
public class HorizontalWheelView extends View {

    public enum ACTION { CLICK, FLING, DRAGGLE }
    public enum DividerType { FILL, WRAP, CIRCLE }

    private DividerType dividerType;
    private Context context;
    private Handler handler;
    private GestureDetector gestureDetector;
    private OnItemSelectedListener onItemSelectedListener;
    private boolean isOptions = false;
    private boolean isCenterLabel = true;
    private ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> mFuture;
    private Paint paintOuterText;
    private Paint paintCenterText;
    private Paint paintIndicator;
    private WheelAdapter adapter;
    private String label;
    private int textSize;
    private int maxTextWidth;
    private int maxTextHeight;
    private int textYOffset;
    private float itemWidth;
    private Typeface typeface = Typeface.MONOSPACE;
    private int textColorOut;
    private int textColorCenter;
    private int dividerColor;
    private int dividerWidth;

    private boolean isLoop;
    private float firstLineX;
    private float secondLineX;
    private float totalScrollX;
    private int initPosition;
    private int selectedItem;
    private int preCurrentIndex;
    private int itemsVisible = 7;
    private int measuredWidth;
    private int measuredHeight;
    private int radius;
    private int mOffset = 0;
    private float previousX = 0;
    private long startTime = 0;
    private static final int VELOCITY_FLING = 5;
    private int heightMeasureSpec;
    private int mGravity = Gravity.CENTER;
    private int drawCenterContentStart = 0;
    private int drawOutContentStart = 0;
    private float CENTER_CONTENT_OFFSET;
    private boolean isAlphaGradient = false;
    private boolean selectRightMost = false;
    private int textIndicatorGap = 14; // px，文字与指示器的间距默认20像素

    // 指示器固定宽度变量（dp）
    private float indicatorFixedWidth = dp2px(24f); // -1表示使用比例模式
    private float indicatorHeight = 8f; // 指示器高度，提升为成员变量

    private int centerTextSize;

    // 自定义item宽度叠加宽度变量
    private int customWidthOffset = 40;

    private final float centerTextSizeOffsetSp = 2.0f; // 选中文字比未选中文字大2sp

    public HorizontalWheelView(Context context) {
        this(context, null);
    }

    public HorizontalWheelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        textSize = getResources().getDimensionPixelSize(com.contrarywind.view.R.dimen.pickerview_textsize);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        float density = dm.density;
        if (density < 1) {
            CENTER_CONTENT_OFFSET = 2.4F;
        } else if (1 <= density && density < 2) {
            CENTER_CONTENT_OFFSET = 4.0F;
        } else if (2 <= density && density < 3) {
            CENTER_CONTENT_OFFSET = 6.0F;
        } else if (density >= 3) {
            CENTER_CONTENT_OFFSET = density * 2.5F;
        }
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, com.contrarywind.view.R.styleable.pickerview, 0, 0);
            mGravity = a.getInt(com.contrarywind.view.R.styleable.pickerview_wheelview_gravity, Gravity.CENTER);
            textColorOut = a.getColor(com.contrarywind.view.R.styleable.pickerview_wheelview_textColorOut, 0xFFa8a8a8);
            textColorCenter = a.getColor(com.contrarywind.view.R.styleable.pickerview_wheelview_textColorCenter, 0xFF2a2a2a);
            dividerColor = a.getColor(com.contrarywind.view.R.styleable.pickerview_wheelview_dividerColor, 0xFFd5d5d5);
            dividerWidth = a.getDimensionPixelSize(com.contrarywind.view.R.styleable.pickerview_wheelview_dividerWidth, 2);
            textSize = a.getDimensionPixelOffset(com.contrarywind.view.R.styleable.pickerview_wheelview_textSize, textSize);
            a.recycle();
        }
        initLoopView(context);
    }

    private void initLoopView(Context context) {
        this.context = context;
        handler = new HorizontalMessageHandler(this);
        gestureDetector = new GestureDetector(context, new HorizontalLoopViewGestureListener(this));
        gestureDetector.setIsLongpressEnabled(false);
        isLoop = true;
        totalScrollX = 0;
        initPosition = -1;
        initPaints();
    }

    private void initPaints() {
        paintOuterText = new Paint();
        paintOuterText.setColor(textColorOut);
        paintOuterText.setAntiAlias(true);
        paintOuterText.setTypeface(typeface);
        paintOuterText.setTextSize(textSize);

        paintCenterText = new Paint();
        paintCenterText.setColor(textColorCenter);
        paintCenterText.setAntiAlias(true);

        // 设置选中item的字体大小（原始大小 + 放大倍数）
        centerTextSize = textSize + (int)(centerTextSizeOffsetSp * context.getResources().getDisplayMetrics().scaledDensity);
        paintCenterText.setTextSize(centerTextSize);
        // 设置选中item字体加粗
        paintCenterText.setTypeface(Typeface.create(typeface, Typeface.BOLD));

        paintIndicator = new Paint();
        paintIndicator.setColor(dividerColor);
        paintIndicator.setAntiAlias(true);
        setLayerType(LAYER_TYPE_SOFTWARE, null);
    }

    private void reMeasure() {
        if (adapter == null) return;
        measureTextWidthHeight();
        int halfCircumference = (int) (itemWidth * (itemsVisible - 1));
        measuredWidth = (int) ((halfCircumference * 2) / Math.PI);
        radius = (int) (halfCircumference / Math.PI);
        measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        firstLineX = (measuredWidth - itemWidth) / 2.0F;
        secondLineX = (measuredWidth + itemWidth) / 2.0F;
        if (initPosition == -1) {
            if (adapter != null && selectRightMost) {
                initPosition = adapter.getItemsCount() - 1;
            } else if (isLoop) {
                initPosition = (adapter.getItemsCount() + 1) / 2;
            } else {
                initPosition = 0;
            }
        }
        preCurrentIndex = initPosition;
    }

    private void measureTextWidthHeight() {
        Rect rect = new Rect();
        maxTextWidth = 0;
        // 使用选中item的字体大小来测量最大宽度，确保有足够空间
        paintCenterText.setTextSize(centerTextSize);
        for (int i = 0; i < adapter.getItemsCount(); i++) {
            String s1 = getContentText(adapter.getItem(i));
            paintCenterText.getTextBounds(s1, 0, s1.length(), rect);
            int textWidth = rect.width();
            if (textWidth > maxTextWidth) {
                maxTextWidth = textWidth;
            }
        }
        paintCenterText.getTextBounds("\u661F\u671F", 0, 2, rect);
        maxTextHeight = rect.height() + 2;
        // 修改itemWidth计算逻辑：maxTextWidth + 自定义宽度变量
        itemWidth = maxTextWidth + customWidthOffset;
        // 恢复字体大小
        paintCenterText.setTextSize(centerTextSize);
    }

    public void smoothScroll(ACTION action) {
        cancelFuture();
        if (action == ACTION.FLING || action == ACTION.DRAGGLE) {
            mOffset = (int) ((totalScrollX % itemWidth + itemWidth) % itemWidth);
            if ((float) mOffset > itemWidth / 2.0F) {
                mOffset = (int) (itemWidth - (float) mOffset);
            } else {
                mOffset = -mOffset;
            }
        }
        mFuture = mExecutor.scheduleWithFixedDelay(new HorizontalSmoothScrollTimerTask(this, mOffset), 0, 10, TimeUnit.MILLISECONDS);
    }

    public final void scrollBy(float velocityX) {
        cancelFuture();
        mFuture = mExecutor.scheduleWithFixedDelay(new HorizontalInertiaTimerTask(this, velocityX), 0, VELOCITY_FLING, TimeUnit.MILLISECONDS);
    }

    public void cancelFuture() {
        if (mFuture != null && !mFuture.isCancelled()) {
            mFuture.cancel(true);
            mFuture = null;
        }
    }

    public final void setCyclic(boolean cyclic) {
        isLoop = cyclic;
    }

    public final void setTypeface(Typeface font) {
        typeface = font;
        paintOuterText.setTypeface(typeface);
        // 选中item字体加粗
        paintCenterText.setTypeface(Typeface.create(typeface, Typeface.BOLD));
    }

    public final void setTextSize(float size) {
        if (size > 0.0F) {
            textSize = (int) (context.getResources().getDisplayMetrics().density * size);
            paintOuterText.setTextSize(textSize);

            // 设置选中item的字体大小（原始大小 + 放大倍数）
            centerTextSize = textSize + (int)(centerTextSizeOffsetSp * context.getResources().getDisplayMetrics().scaledDensity);
            paintCenterText.setTextSize(centerTextSize);
        }
    }

    public final void setCurrentItem(int currentItem) {
        this.selectedItem = currentItem;
        this.initPosition = currentItem;
        totalScrollX = 0;
        invalidate();
        // 添加回调触发
        onItemSelected();
    }

    /**
     * 新增：带动画的setCurrentItem
     * @param target 目标item
     * @param smoothScroll 是否平滑滚动
     */
    public void setCurrentItem(final int target, boolean smoothScroll) {
        if (!smoothScroll) {
            setCurrentItem(target);
            return;
        }
        if (adapter == null) return;
        int current = getCurrentItem();
        if (target == current) return;

        // 计算目标和当前的距离
        final int distance = target - current;
        final float startScrollX = totalScrollX;
        final float deltaScrollX = distance * itemWidth;

        // 动画时长和帧数
        final int duration = 300; // ms
        final int frameCount = 30;
        final float perFrame = deltaScrollX / frameCount;

        // 取消之前的动画
        cancelFuture();

        mFuture = mExecutor.scheduleAtFixedRate(new Runnable() {
            int frame = 0;
            @Override
            public void run() {
                post(() -> {
                    if (frame < frameCount) {
                        totalScrollX = startScrollX + perFrame * frame;
                        invalidate();
                        frame++;
                    } else {
                        // 动画结束，设置到目标item
                        setCurrentItem(target);
                        cancelFuture();
                    }
                });
            }
        }, 0, duration / frameCount, TimeUnit.MILLISECONDS);
    }

    public final void setOnItemSelectedListener(OnItemSelectedListener OnItemSelectedListener) {
        this.onItemSelectedListener = OnItemSelectedListener;
    }

    public final void setAdapter(WheelAdapter adapter) {
        this.adapter = adapter;
        reMeasure();
        invalidate();
    }

    public void setItemsVisibleCount(int visibleCount) {
        if (visibleCount % 2 == 0) {
            visibleCount += 1;
        }
        this.itemsVisible = visibleCount + 2;
    }

    public void setAlphaGradient(boolean alphaGradient) {
        isAlphaGradient = alphaGradient;
    }

    public final WheelAdapter getAdapter() {
        return adapter;
    }

    public final int getCurrentItem() {
        if (adapter == null) {
            return 0;
        }
        if (isLoop && (selectedItem < 0 || selectedItem >= adapter.getItemsCount())) {
            return Math.max(0, Math.min(Math.abs(Math.abs(selectedItem) - adapter.getItemsCount()), adapter.getItemsCount() - 1));
        }
        return Math.max(0, Math.min(selectedItem, adapter.getItemsCount() - 1));
    }

    public final void onItemSelected() {
        if (onItemSelectedListener != null) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    onItemSelectedListener.onItemSelected(getCurrentItem());
                }
            }, 200L);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (adapter == null) return;
        initPosition = Math.min(Math.max(0, initPosition), adapter.getItemsCount() - 1);
        int change = (int) (totalScrollX / itemWidth);
        try {
            preCurrentIndex = initPosition + change % adapter.getItemsCount();
        } catch (ArithmeticException e) {
        }
        if (!isLoop) {
            if (preCurrentIndex < 0) preCurrentIndex = 0;
            if (preCurrentIndex > adapter.getItemsCount() - 1) preCurrentIndex = adapter.getItemsCount() - 1;
        } else {
            if (preCurrentIndex < 0) preCurrentIndex = adapter.getItemsCount() + preCurrentIndex;
            if (preCurrentIndex > adapter.getItemsCount() - 1) preCurrentIndex = preCurrentIndex - adapter.getItemsCount();
        }
//        // 绘制中间两条竖线
//        if (dividerType == DividerType.WRAP) {
//            float startY, endY;
//            if (TextUtils.isEmpty(label)) {
//                startY = (measuredHeight - maxTextHeight) / 2 - 12;
//            } else {
//                startY = (measuredHeight - maxTextHeight) / 4 - 12;
//            }
//            if (startY <= 0) startY = 10;
//            endY = measuredHeight - startY;
//            canvas.drawLine(firstLineX, startY, firstLineX, endY, paintIndicator);
//            canvas.drawLine(secondLineX, startY, secondLineX, endY, paintIndicator);
//        } else if (dividerType == DividerType.CIRCLE) {
//            paintIndicator.setStyle(Paint.Style.STROKE);
//            paintIndicator.setStrokeWidth(dividerWidth);
//            float startY, endY;
//            if (TextUtils.isEmpty(label)) {
//                startY = (measuredHeight - maxTextHeight) / 2f - 12;
//            } else {
//                startY = (measuredHeight - maxTextHeight) / 4f - 12;
//            }
//            if (startY <= 0) startY = 10;
//            endY = measuredHeight - startY;
//            float radius = Math.max((endY - startY), itemWidth) / 1.8f;
//            canvas.drawCircle(measuredWidth / 2f, measuredHeight / 2f, radius, paintIndicator);
//        } else {
//            canvas.drawLine(firstLineX, 0.0F, firstLineX, measuredHeight, paintIndicator);
//            canvas.drawLine(secondLineX, 0.0F, secondLineX, measuredHeight, paintIndicator);
//        }

        // 只显示选中项Label文字的模式，并且Label文字不为空，则进行绘制
        float centerX = measuredWidth / 2f;
        if (!TextUtils.isEmpty(label) && isCenterLabel) {
            int drawBottomContentStart = measuredHeight - getTextHeight(paintCenterText, label);
            canvas.drawText(label, centerX, drawBottomContentStart - CENTER_CONTENT_OFFSET, paintCenterText);
        }

        // 先遍历，找到最接近centerX的item
        float minDistance = Float.MAX_VALUE;
        int selectedIdx = -1;
        int selectedCounter = -1;
        float[] drawTextXs = new float[itemsVisible];
        String[] contentTexts = new String[itemsVisible];
        int[] indices = new int[itemsVisible];
        int[] centerYs = new int[itemsVisible];
        int[] outYs = new int[itemsVisible];
        Rect textRect = new Rect();

        // 计算滑动偏移量，确保一致性
        float scrollOffset = totalScrollX % itemWidth;

        for (int counter = 0; counter < itemsVisible; counter++) {
            int index = preCurrentIndex - (itemsVisible / 2 - counter);
            Object showText;
            if (isLoop) {
                index = getLoopMappingIndex(index);
                showText = adapter.getItem(index);
            } else if (index < 0) {
                showText = "";
            } else if (index > adapter.getItemsCount() - 1) {
                showText = "";
            } else {
                showText = adapter.getItem(index);
            }
            String contentText;
            if (!isCenterLabel && !TextUtils.isEmpty(label) && !TextUtils.isEmpty(getContentText(showText))) {
                contentText = getContentText(showText) + label;
            } else {
                contentText = getContentText(showText);
            }
            reMeasureTextSize(contentText);
            measuredCenterContentStart(contentText);
            measuredOutContentStart(contentText);
            centerYs[counter] = drawCenterContentStart;
            outYs[counter] = drawOutContentStart;
            paintCenterText.getTextBounds(contentText, 0, contentText.length(), textRect);
            float textWidth = textRect.width();

            // 计算每个item的中心位置
            float itemCenterX = centerX + (counter - itemsVisible / 2) * itemWidth - scrollOffset;

            // 计算item的左边界（基于item中心位置）
            float itemLeft = itemCenterX - itemWidth / 2f;

            // 让文本在itemWidth区域内水平居中
            float drawTextX = itemLeft + (itemWidth - textWidth) / 2f;

            float distance = Math.abs(itemCenterX - centerX);
            if (distance < minDistance) {
                minDistance = distance;
                selectedIdx = index;
                selectedCounter = counter;
            }
            drawTextXs[counter] = drawTextX;
            contentTexts[counter] = contentText;
            indices[counter] = index;
        }
        // 再遍历绘制
        for (int counter = 0; counter < itemsVisible; counter++) {
            if (counter == selectedCounter) {
                canvas.drawText(contentTexts[counter], drawTextXs[counter], centerYs[counter], paintCenterText);
            } else {
                canvas.drawText(contentTexts[counter], drawTextXs[counter], outYs[counter], paintOuterText);
            }
        }
        selectedItem = selectedIdx;

        // 底部高亮指示条
        float indicatorWidth;
        if (indicatorFixedWidth > 0) {
            indicatorWidth = indicatorFixedWidth;
        } else {
            indicatorWidth = itemWidth * 0.6f;
        }
        float center = getWidth() / 2f;
        paintIndicator.setColor(context.getColor(R.color.c_21d9d9)); // 高亮色
        float indicatorY = measuredHeight - indicatorHeight;
        float rx = indicatorHeight; // 圆角半径
        canvas.drawRoundRect(
                center - indicatorWidth / 2,
                indicatorY,
                center + indicatorWidth / 2,
                indicatorY + indicatorHeight,
                rx,
                rx,
                paintIndicator
        );
    }

    private void setOutPaintStyle(float offsetCoefficient, float angle) {
        float DEFAULT_TEXT_TARGET_SKEW_X = 0.5f;
        int multiplier = 0;
        if (textYOffset > 0) {
            multiplier = 1;
        } else if (textYOffset < 0) {
            multiplier = -1;
        }
        paintOuterText.setTextSkewX(multiplier * (angle > 0 ? -1 : 1) * DEFAULT_TEXT_TARGET_SKEW_X * offsetCoefficient);
        int alpha = isAlphaGradient ? (int) ((90F - Math.abs(angle)) / 90f * 255) : 255;
        paintOuterText.setAlpha(alpha);
    }

    private void reMeasureTextSize(String contentText) {
        // 在测量之前，将油漆尺寸重置为其基础值
        paintCenterText.setTextSize(centerTextSize);
        paintOuterText.setTextSize(textSize);

        Rect rect = new Rect();
        // 用大的字体测量
        paintCenterText.getTextBounds(contentText, 0, contentText.length(), rect);
        int height = rect.height();

        // 如果较大的文本超出视图的高度，则按比例缩小两者
        if (height > measuredHeight) {
            float scale = (float) measuredHeight / height;
            paintCenterText.setTextSize(centerTextSize * scale);
            paintOuterText.setTextSize(textSize * scale);
        }
    }

    private int getLoopMappingIndex(int index) {
        if (index < 0) {
            index = index + adapter.getItemsCount();
            index = getLoopMappingIndex(index);
        } else if (index > adapter.getItemsCount() - 1) {
            index = index - adapter.getItemsCount();
            index = getLoopMappingIndex(index);
        }
        return index;
    }

    private String getContentText(Object item) {
        if (item == null) {
            return "";
        } else if (item instanceof IPickerViewData) {
            return ((IPickerViewData) item).getPickerViewText();
        } else if (item instanceof Integer) {
            return String.format("%02d", (int) item);
        }
        return item.toString();
    }

    private void measuredCenterContentStart(String content) {
        Rect rect = new Rect();
        paintCenterText.getTextBounds(content, 0, content.length(), rect);
        switch (mGravity) {
            case Gravity.CENTER:
                if (isOptions || label == null || label.equals("") || !isCenterLabel) {
                    drawCenterContentStart = (int) ((measuredHeight - rect.height()) * 0.5);
                } else {
                    drawCenterContentStart = (int) ((measuredHeight - rect.height()) * 0.25);
                }
                break;
            case Gravity.TOP:
                drawCenterContentStart = 0;
                break;
            case Gravity.BOTTOM:
                Rect rectBtm = new Rect();
                paintCenterText.getTextBounds(content, 0, content.length(), rectBtm);
                drawCenterContentStart = (int) (measuredHeight - indicatorHeight - textIndicatorGap - rectBtm.bottom);
                break;
        }
    }

    private void measuredOutContentStart(String content) {
        Rect rect = new Rect();
        paintOuterText.getTextBounds(content, 0, content.length(), rect);
        switch (mGravity) {
            case Gravity.CENTER:
                if (isOptions || label == null || label.equals("") || !isCenterLabel) {
                    drawOutContentStart = (int) ((measuredHeight - rect.height()) * 0.5);
                } else {
                    drawOutContentStart = (int) ((measuredHeight - rect.height()) * 0.25);
                }
                break;
            case Gravity.TOP:
                drawOutContentStart = 0;
                break;
            case Gravity.BOTTOM:
                drawOutContentStart = (int) (measuredHeight - indicatorHeight - textIndicatorGap - rect.bottom);
                break;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        this.heightMeasureSpec = heightMeasureSpec;
        reMeasure();
        setMeasuredDimension(measuredWidth, measuredHeight);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean eventConsumed = gestureDetector.onTouchEvent(event);
        boolean isIgnore = false;
        float left = -initPosition * itemWidth;
        float right = (adapter.getItemsCount() - 1 - initPosition) * itemWidth;
        float ratio = 0.25f;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startTime = System.currentTimeMillis();
                cancelFuture();
                previousX = event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = previousX - event.getRawX();
                previousX = event.getRawX();
                totalScrollX = totalScrollX + dx;
                if (!isLoop) {
                    if ((totalScrollX - itemWidth * ratio < left && dx < 0)
                            || (totalScrollX + itemWidth * ratio > right && dx > 0)) {
                        totalScrollX -= dx;
                        isIgnore = true;
                    } else {
                        isIgnore = false;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            default:
                if (!eventConsumed) {
                    // 检查是否是快速点击（小于120ms）
                    boolean isQuickClick = (System.currentTimeMillis() - startTime) <= 120;

                    if (isQuickClick) {
                        // 快速点击：计算点击的目标item
                        float x = event.getX();
                        float centerX = measuredWidth / 2f;

                        // 计算点击位置相对于中心的偏移
                        float clickOffset = x - centerX;

                        // 计算点击的是第几个item（相对于中心item）
                        int clickedItemOffset = Math.round(clickOffset / itemWidth);

                        // 计算目标item索引
                        int currentItem = getCurrentItem();
                        int targetItem = currentItem + clickedItemOffset;

                        // 边界检查
                        if (isLoop) {
                            // 循环模式下处理索引越界
                            if (targetItem < 0) {
                                targetItem = adapter.getItemsCount() + targetItem;
                            } else if (targetItem >= adapter.getItemsCount()) {
                                targetItem = targetItem - adapter.getItemsCount();
                            }
                        } else {
                            // 非循环模式下限制在有效范围内
                            targetItem = Math.max(0, Math.min(targetItem, adapter.getItemsCount() - 1));
                        }

                        // 使用平滑滚动到目标item
                        setCurrentItem(targetItem, true);
                    } else {
                        // 拖拽结束：使用原有的平滑滚动逻辑
                        mOffset = (int) ((totalScrollX % itemWidth + itemWidth) % itemWidth);
                        if ((float) mOffset > itemWidth / 2.0F) {
                            mOffset = (int) (itemWidth - (float) mOffset);
                        } else {
                            mOffset = -mOffset;
                        }
                        smoothScroll(ACTION.DRAGGLE);
                    }
                }
                break;
        }
        if (!isIgnore && event.getAction() != MotionEvent.ACTION_DOWN) {
            invalidate();
        }
        return true;
    }

    @Override
    protected void onDetachedFromWindow() {
        cancelFuture();
        super.onDetachedFromWindow();
    }

    public int getItemsCount() {
        return adapter != null ? adapter.getItemsCount() : 0;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public void isCenterLabel(boolean isCenterLabel) {
        this.isCenterLabel = isCenterLabel;
    }

    public void setGravity(int gravity) {
        this.mGravity = gravity;
    }

    public int getTextHeight(Paint paint, String str) {
        int iRet = 0;
        if (str != null && str.length() > 0) {
            int len = str.length();
            float[] heights = new float[len];
            paint.getTextWidths(str, heights);
            for (int j = 0; j < len; j++) {
                iRet += (int) Math.ceil(heights[j]);
            }
        }
        return iRet;
    }

    public void setIsOptions(boolean options) {
        isOptions = options;
    }

    public void setTextColorOut(int textColorOut) {
        this.textColorOut = textColorOut;
        paintOuterText.setColor(this.textColorOut);
    }

    public void setTextColorCenter(int textColorCenter) {
        this.textColorCenter = textColorCenter;
        paintCenterText.setColor(this.textColorCenter);
    }

    public void setTextYOffset(int textYOffset) {
        this.textYOffset = textYOffset;
        if (textYOffset != 0) {
            paintCenterText.setTextScaleX(1.0f);
        }
    }

    public void setDividerWidth(int dividerWidth) {
        this.dividerWidth = dividerWidth;
        paintIndicator.setStrokeWidth(dividerWidth);
    }

    public void setDividerColor(int dividerColor) {
        this.dividerColor = dividerColor;
        paintIndicator.setColor(dividerColor);
    }

    public void setDividerType(DividerType dividerType) {
        this.dividerType = dividerType;
    }

    public boolean isLoop() {
        return isLoop;
    }

    public float getTotalScrollX() {
        return totalScrollX;
    }

    public void setTotalScrollX(float totalScrollX) {
        this.totalScrollX = totalScrollX;
    }

    public float getItemWidth() {
        return itemWidth;
    }

    public int getInitPosition() {
        return initPosition;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    public void notifyDataSetChanged() {
        reMeasure();
        requestLayout();
        invalidate();
    }

    public void setSelectRightMost(boolean selectRightMost) {
        this.selectRightMost = selectRightMost;
        if (adapter != null && selectRightMost) {
            int last = adapter.getItemsCount() - 1;
            setCurrentItem(last);
        }
    }

    /** 设置文字与指示器的间距（单位：像素） */
    public void setTextIndicatorGap(int gapPx) {
        this.textIndicatorGap = gapPx;
        invalidate();
    }

    /** 设置指示器高度（单位：像素） */
    public void setIndicatorHeight(float heightPx) {
        this.indicatorHeight = heightPx;
        invalidate();
    }

    /**
     * 设置自定义宽度偏移量
     * @param customWidthOffset 自定义宽度偏移量（单位：像素）
     */
    public void setCustomWidthOffset(int customWidthOffset) {
        this.customWidthOffset = customWidthOffset;
        if (adapter != null) {
            reMeasure();
            invalidate();
        }
    }

    /**
     * 设置指示器固定宽度
     * @param widthPx 固定宽度（dp），设置为-1则使用默认比例模式
     */
    public void setIndicatorFixedWidth(float widthPx) {
        this.indicatorFixedWidth = widthPx;
        invalidate();
    }

    /**
     * 获取自定义宽度偏移量
     * @return 自定义宽度偏移量（单位：像素）
     */
    public int getCustomWidthOffset() {
        return customWidthOffset;
    }

    /**
     * 获取选中item字体放大倍数
     * @return 字体放大倍数（单位：sp）
     */
    public float getCenterTextSizeOffsetSp() {
        return centerTextSizeOffsetSp;
    }

} 